package com.jhgsys.internal.common.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jhgsys.internal.common.authentication.BaseThreadDataStorage;
import com.jhgsys.internal.common.authentication.ShiroHelper;
import com.jhgsys.internal.common.constant.DictCodeConstant;
import com.jhgsys.internal.common.controller.base.ResultController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.contractor.entity.BaseContractor;
import com.jhgsys.internal.contractor.service.IBaseContractorService;
import com.jhgsys.internal.dict.entity.DictItem;
import com.jhgsys.internal.dict.service.IDictService;
import com.jhgsys.internal.system.dto.TenantDto;
import com.jhgsys.internal.system.entity.*;
import com.jhgsys.internal.system.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;

import java.util.*;

/**
 * @author MrBird
 */
public class BaseController extends ResultController {

    @Autowired
    private ITenantService tenantService;

    @Autowired
    private IDictService dictService;

    @Autowired
    private IBaseContractorService baseContractorService;

    @Autowired
    private IPostService postService;

    @Autowired
    private ShiroHelper shiroHelper;

    @Autowired
    IUserRoleService userRoleService;

    @Autowired
    private IUserService userService;

    protected static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    protected User getCurrentUser() {
        return (User) getSubject().getPrincipal();
    }

    protected Session getSession() {
        return getSubject().getSession();
    }

    protected Session getSession(Boolean flag) {
        return getSubject().getSession(flag);
    }

    protected void login(AuthenticationToken token) {
        getSubject().login(token);
    }

    protected Map<String, Object> getDataTable(IPage<?> pageInfo) {
        Map<String, Object> data = new HashMap<>();
        data.put("rows", pageInfo.getRecords());
        data.put("total", pageInfo.getTotal());
        return data;
    }

    /**
     * 判断是否是系统管理员权限
     * @return
     */
    protected boolean hasAdminRole() {
        boolean hasAdminRole = false;
        String tenantId = getCurrentUser().getTenantId();
        TenantDto tenantByTenantId = tenantService.findTenantByTenantId(tenantId);
        if(null != tenantByTenantId && "0".equals(tenantByTenantId.getTenantCategory())){
            hasAdminRole =  true;
        }
        return hasAdminRole;
    }

    protected boolean isAdmin() {
        boolean hasAdminRole = false;
        String userid = getCurrentUser().getUserId();
        List<UserRole>  userRoleList = userRoleService.getUserRoleListByUserid(userid);
         if(CollectionUtils.isNotEmpty(userRoleList)){
             for(UserRole  userRole:userRoleList){
                 if(userRole.getRoleId().equals("1")){
                     hasAdminRole=true;
                     break;
                 }
             }
         }
        return hasAdminRole;
    }

    /**
     * 判断当前登陆人是项目经理还是操作员，是项目经理返回1，是操作员返回2，两者都是或者是系统管理员返回3
     * @return
     */
    protected int isPmRole() {
        int roleVal = 0;
        //是否项目经理
        boolean isPm = false;
        //是否操作（检验）员
        boolean isOp = false;
        //是否系统管理员
        boolean isSysAdmin = false;
        String userid = getCurrentUser().getUserId();
        List<UserRole>  userRoleList = userRoleService.getUserRoleListByUserid(userid);
        if(CollectionUtils.isNotEmpty(userRoleList)){
            isPm = userRoleList.stream().anyMatch(userRole -> Objects.equals(userRole.getRoleId(), "36452c0006d83ec81491953ab53d651b"));
            isOp = userRoleList.stream().anyMatch(userRole -> Objects.equals(userRole.getRoleId(), "533f1044ed1db628316a3e7c35305fd8"));
            isSysAdmin = userRoleList.stream().anyMatch(userRole -> Objects.equals(userRole.getRoleId(), "1"));
        }
        if (isPm){
            roleVal = 1;
        }else if(isOp){
            roleVal = 2;
        }
        if((isPm && isOp) || isSysAdmin){
            roleVal = 3;
        }
        return roleVal;
    }

    /**
     * 判断是否是总公司权限
     * @return
     */
    protected boolean hasHeadCompanyRole() {
        boolean hasHeadCompanyRole = false;
        String tenantId = getCurrentUser().getTenantId();
        TenantDto tenantByTenantId = tenantService.findTenantByTenantId(tenantId);
        if(null != tenantByTenantId && "1".equals(tenantByTenantId.getTenantCategory())){
            hasHeadCompanyRole =  true;
        }
        return hasHeadCompanyRole;
    }
    /**
     * 获取当前用户类型
     * @return
     */
    protected String getCurrentUserId (){
        String userId = null;
        User currentUser = getCurrentUser();
        if(null != currentUser){
            userId = currentUser.getUserId();
        }
        return userId;
    }
    /**
     * 获取当前用户类型
     * @return
     */
    protected String getCurrentUserType (){
        String Utype = null;
        String tenantId = getCurrentUser().getTenantId();
        TenantDto tenantByTenantId = tenantService.findTenantByTenantId(tenantId);
        if(null != tenantByTenantId && StringUtils.isNotBlank(tenantByTenantId.getTenantCategory())){
            Utype =  tenantByTenantId.getTenantCategory();
        }
        return Utype;
    }
    /**
     * 获取当前用户所属公司Id
     * @return
     */
    protected String getCurrentTenantId(){
        String tenantId = getCurrentUser().getTenantId();
        if(StringUtils.isBlank(tenantId)){
            tenantId = FebsConstant.UNKNOWN_TENANT_ID;
        }
        return tenantId;
    }

    /**
     * 获取所属公司承包商
     * @return
     */
    protected List<BaseContractor> getBaseContractors(String tenantId){
        BaseContractor baseContractor = new BaseContractor();
        baseContractor.setTenantId(tenantId);
        List<BaseContractor> baseContractors = baseContractorService.findBaseContractors(baseContractor);
        return baseContractors;
    }

    /**
     * 根据获取通过登录用户token
     * @return
     */
    protected String getLoginToken() {
        String token = ""+ BaseThreadDataStorage.get(BaseThreadDataStorage.TOKEN_KEY);
        return token;
    }

    /**
     * 获取管理公司
     * @return
     */
    protected List<TenantDto> getTenantList(){
        List<TenantDto> tenantList = new ArrayList<>();
        if(hasAdminRole () ||hasHeadCompanyRole()){
            Tenant tenant = new Tenant();
            tenant.setStatus("1");
            tenantList = tenantService.findTenantList(tenant);
        }else{
            String currentTenantId = getCurrentTenantId();
            TenantDto currentTenant = tenantService.findTenantByTenantId(currentTenantId);
            if(null == currentTenant || StringUtils.isBlank(currentTenant.getTenantId())){
                currentTenant.setTenantId(FebsConstant.UNKNOWN_TENANT_ID);
                currentTenant.setTenantName("未知归属，请联系管理员");
            }
            tenantList.add(currentTenant);
        }
        return  tenantList;
    }

    /**
     * 给model设置数据字典
     * @return
     */
    protected void setModelDict(Model model){
        List<DictItem> dictItems = new ArrayList<>();
        //公司分类
        dictItems = dictService.findDictByCode(DictCodeConstant.SAFETY_COMPANY_TYPE);
        if(CollectionUtils.isNotEmpty(dictItems)){
            model.addAttribute("tenantTypeList",dictItems);
        }
    }

    protected List<Post> getPostByTenantId(String tenantId){
        Post post = new Post();
        post.setTenantId(tenantId);
        List<Post> postList = postService.findDeptForm(post);
        return postList;
    }

    /**
     * 判断是否是某个模块的管理员
     * @param ModelName
     * @See com.jhgsys.internal.common.constant.ModuleManagerPermissionConstant 模块管理员权限配置
     * @return
     */
    protected boolean hasPermission(String ModelName) {
        boolean isModuleManager = false;
        AuthorizationInfo authorizationInfo = shiroHelper.getCurrentuserAuthorizationInfo();
        if(authorizationInfo.getStringPermissions().contains(ModelName)){
            isModuleManager =  true;
        }
        return isModuleManager;
    }

    /**
     * 根据角色id和部门id获取人员信息
     * @param roleId
     * @param tenantId
     * @return
     */
    public List<User> getUsersByRoleId(String roleId, String tenantId){
        List<User> userByRole = userService.findByRoleId(roleId, tenantId);
        return userByRole;
    }

}
